package com.rpc.example.serial;

import com.alibaba.fastjson.JSON;
import com.rpc.example.constant.SerializeTypeEnum;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *  
 *  
 * @author Elvis
 * @version 1.0, 2022/11/10
 */
public class JavaSerialize implements ISerial {

    @Override
    public <T> byte[] serialized(T message) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ObjectOutputStream oot = new ObjectOutputStream(out)) {
            oot.writeObject(message);
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream oot = new ObjectInputStream(in);
            return (T) oot.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte getSerializeType() {
        return SerializeTypeEnum.JSON.getCode();
    }
}
